// pages/login/login.js
var app = getApp();
var getInvite = require("../../mybehaviors/getInvite/getInvite");
var int = app.globalData.statusBarHeight * 2 + 40;
const menuButtonObject = wx.getMenuButtonBoundingClientRect().height;
const skinBehavior = require("../../utils/themeSkin/skinBehavior");
Page({
  behaviors: [getInvite,skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: int + menuButtonObject,
    yzredirect: "",
    logintap: false,
    // 兼容登录
    canIUseGetUserProfile:false,
    showAutoBindPhone: false, // 首次授权登录自动绑定手机号(PS：新会员！！！首次)
    showChangeID: false,
    changidInfo: {
      uid: null,
      change_uid: null,
    },
    AuthorizedPhone: '',
    // 余额
    balance:'余额',
    // 积分
    point:'积分',
    default_head_img:`${app.globalData.imgPath}photo-mr.jpg`,
    shop_name: "",
    checkedSelect: false,
    theme_color: "",
    tipsShow: false,
    platform_protocol: false,
    register_protocol: false,
    popoverProtocolContent: {
      title: "",
      conten: ""
    },
    openAgreement: false,
    isHiddenNoLogin: true,
    loginOut:false,
    // 手机号登录或者验证码登录
    otherLogin:false,
    country_code:0,
    btnText: '获取验证码',
    btnTag:false,
    timer: null,
    loginToSwitch: { //是否显示登录方式切换
      mobile_login_code: '',
      is_enable: '',
    },
    form:{
      // 区号
      country:"86",
      // 密码
      password:"",
      // 手机号
      mobile:"",
      // 图形验证码
      captcha:"",
      // 短信验证码
      code:"",
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.yzredirect = app.getyzredirect();
    if(this.options.extra_data) {
      this.setData({
        isHiddenNoLogin: false
      });
      this.checkLogin();//验证是否登录
    } 
    this.getData();
    if (wx.getUserProfile) {
      // 是否兼容getUserProfile
      this.setData({
        canIUseGetUserProfile: true
      });
    }
  },
  comfirm(){
    this.setData({
      checkedSelect:true,
      tipsShow:false
    })
  },
  closeTipsShow(){
    this.setData({
      tipsShow:false
    })
  },
  tapShowAgreement(e){
    let {key} = e.currentTarget.dataset;
    if(key == 'register'){
      this.setData({
        openAgreement:true,
        'popoverProtocolContent.title':this.data.register_protocol.title,
        'popoverProtocolContent.content':this.data.register_protocol.content
      })
    }else{
      this.setData({
        openAgreement:true,
        'popoverProtocolContent.title':this.data.platform_protocol.title,
        'popoverProtocolContent.content':this.data.platform_protocol.content
      })
    }
  },
  PlatformAgreementClose() {
    this.setData({
      openAgreement: false
    });
  },
  PlatformAgreementOnChange(e) {
    this.setData({
      checkedSelect: e.detail
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.options.isOut == 1){
      this.newLoginInformation();
    }
  },
  // onHide: function (){
  //   app.data.login_type = 1;
  // },
  // onUnload: function (){
  //   app.data.login_type = 1;
  // },
  bindInp(e){
    let {key} = e.currentTarget.dataset;
    let val = e.detail;
    // this.data.form[key] = val
    this.setData({
      ['form.'+key]:val
    })
    this.loginButtonStatus();
  },
  mobile_login(){
    if (this.data.logintap) {
      console.log('正在请求');
      return;
    }
    this.data.logintap = true;
    if(app._isTextEmpty(this.data.form.mobile)){
      app.tips('请填写手机号')
      return
    }
    if(this.data.mobile_login_code == 1){
      if(app._isTextEmpty(this.data.form.code)){
        app.tips('请填写验证码')
        return
      }
    }
    if (this.data.phoneAndPassword || this.data.accountAndPasswordLogin) {
      if (app._isTextEmpty(this.data.form.password)) {
        app.tips("请填写密码");
        return;
      }
      delete this.data.form.code;
    }
    this.data.form.uuid = 0;
    let mid = wx.getStorageSync('mid');
    this.data.form.mid =  mid?mid:0;
    this.data.form.is_sms = this.data.mobile_login_code;
    if(this.data.mobile_login_code != 1){
      delete this.data.form.code;
    }
    this.login(this.data.form)
  },
  async login(data_form){
    data_form.ver = '3';
    data_form.info = "";
    data_form.login_param = app.globalData.loginScene;
    console.log(data_form)
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("member.login.index"),
      data:data_form
    })
    let _data = data;
    if ( data.result ){
      try {
        // 存储key
        if (_data.data.user_info) {
          wx.setStorageSync("nickname", _data.data.user_info.nickname);
        }
        if(_data.data.session){
          wx.setStorageSync('session', _data.data.session);
        }
        if(_data.data.openid) {
          wx.setStorageSync('openid', _data.data.openid);
        }
        if(_data.data.wx_token){
          wx.setStorageSync('wx_token', _data.data.wx_token);
        }
        if(_info){
          wx.setStorageSync('userInfo', _info);
        }
        if(_data.data.uid){
          wx.setStorageSync('yz_uid', _data.data.uid);
        }

        wx.hideLoading();
        if(this.options.extra_data) {
          that.skipLogin();
        } 
        if( _data.data.is_first_time_bind){
          // 首次授权登录自动绑定手机号
          that.setData({
            showAutoBindPhone: true
          });
        }else{
          that.getInviteData();
        }

        wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
      } catch (e) {
        wx.reLaunch({
          url: "/packageG/index/index",
        });
      }
    } else {
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: _data.msg
      });
      if(this.data.timer){
        this.data.btnTag = false;
        this.setData({
          btnText:"获取验证码"
        })
        clearInterval(this.data.timer);
        this.data.timer = null;
      }
      console.log("第三方登录数据错误" + data.msg);
    }
    this.data.logintap = false;
  },
  async verificationCode(){
    if (this.data.btnTag) return
    if (app._isTextEmpty(this.data.form.country)) {
      app.tips("请输入国际区号");
      return;
    }
    if (app._isTextEmpty(this.data.form.mobile)) {
      app.tips("请填写手机号");
      return;
    }

    if (this.data.form.country == "86" && app._isMoblie(this.data.form.mobile)) {
      app.tips("请填写正确的手机号");
      return;
    }

    if (this.data.imgcode && this.data.mobile_login_code == 1 && app._isTextEmpty(this.data.form.captcha)) {
      app.tips("请填写图形验证码");
      return;
    }
    wx.showLoading({
      title: '发送中',
    })
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("member.register.alySendCode"),
      data:{
        mobile: this.data.form.mobile,
        captcha: this.data.form.captcha,
        sms_type: 3,
        state: this.data.form.country,
        key:this.data.imgKey
      }
    })
    wx.hideLoading();
    if(data.result == 1){
      this.sendCodeAnimation();
    }else{
      this.setData({
        captcha:""
      })
      app.tips(data.msg)
      this.getimgdata();
    }
  },
  sendCodeAnimation(){
    const TIME_COUNT = 60;
    if (!this.data.timer) {
      this.data.count = TIME_COUNT;
      wx.showToast({
        title:'验证码已发送'
      });
      this.data.timer = setInterval(() => {
        if (this.data.count > 0 && this.data.count <= TIME_COUNT) {
          this.data.count--;
          this.setData({
            btnText:this.data.count + "s后重新获取"
          })
          this.data.btnTag = true;
        } else {
          this.data.btnTag = false;
          this.setData({
            btnText:"获取验证码"
          })
          clearInterval(this.data.timer);
          this.data.timer = null;
        }
      }, 1000);
    }
  },
  onClose(){
    this.setData({
      otherLogin:false
    })
  },
  tapLoginOther(){
    if(this.data.register_protocol || this.data.platform_protocol){
      if (!this.data.checkedSelect) {
        this.setData({
          tipsShow : true
        })
        return;
      }
    }
    this.setData({
      otherLogin:true
    })
  },
  async getimgdata(){
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("home-page.getCaptcha")
    })
    if(data.result){
      this.setData({
        imgcode: data.data.captcha.img,
        imgKey : data.data.captcha.key
      })
    }
  },
  tapChange(e){
    let {key} = e.currentTarget.dataset;
    if(key == 'phoneAndPassword'){
      this.setData({
        phoneAndPassword:true,
        mobile_login_code:0,
        'form.password':''
      })
    } else {
      this.setData({
        mobile_login_code:1,
        phoneAndPassword:false,
        'form.code':''
      })
    }
    this.loginButtonStatus();
  },
  loginButtonStatus(){
    if(this.data.phoneAndPassword){
      console.log(this.data.form.password,this.data.form.mobile)
      if(this.data.form.password && this.data.form.mobile){
        this.setData({
          loginStatus:true
        })
        return
      }
    } else if(this.data.mobile_login_code == 1 && this.data.is_enable == 0){
      console.log(this.data.form.password,this.data.form.code)
      if(this.data.form.mobile && this.data.form.code){
        this.setData({
          loginStatus:true
        })
        return
      }
    }
    this.setData({
      loginStatus:false
    })
  },
  async newLoginInformation(){
    let {
      data
    } = await app._postNetWork({
      url: app.getNetAddresss("member.login.new-login-mode")
    })
    if(data.result){
      this.setData({
        // 区号开关
        country_code: data.data.country_code,
        //mobile_login_code 手机验证码登录：0关闭1开启
        mobile_login_code: data.data.mobile_code_login,
        // 密码登录：0关闭1开启
        is_enable: data.data.password_login,
        'loginToSwitch.mobile_login_code':data.data.mobile_code_login,
        'loginToSwitch.is_enable':data.data.password_login
      })
      //判断是否为手机号密码
      if (this.data.enable_btn != '1' && this.data.is_enable == 1) { 
        // phoneAndPassword 账号密码登录
        this.setData({
          phoneAndPassword: true
        })
      }
      //如果两种登陆都开启了并且手机验证码登陆也开启了就默认显示手机验证码登陆并且显示切换按钮
      if (this.data.mobile_login_code && this.data.is_enable || this.data.enable_btn == '1') { 
        if(this.data.mobile_login_code == 1){
          this.setData({
            phoneAndPassword:false,
            is_enable:false
          })
        }
        //登陆方式切换按钮是否显示
        this.setData({
          loginModeSwitchButton:true
        })
      }
      if(data.data.sms && data.data.sms.captcha.status == "1"){
        this.setData({
          imgKey : data.data.sms.captcha.key
        })
        this.setData({
          // 图片验证码
          imgcode: data.data.sms.captcha.img
        })
      }
      this.setData({
        // otherLogin:true,
        loginOut:true
      })
    }else{
      app.tips(data.msg)
    }
  },
  getUserProfileTap(e) {
    if(this.data.register_protocol || this.data.platform_protocol){
      if (!this.data.checkedSelect) {
        this.setData({
          tipsShow : true
        })
        return;
      }
    }

    if (this.data.logintap) {
      // 正在请求 return
      console.log('正在请求');
      return;
    }
    this.setData({
      logintap: true
    });
    wx.showLoading({
      title: '登录中',
    });
    if(this.data.canIUseGetUserProfile){
      wx.getUserProfile({
        desc: '获取用户信息',
        success: (_info)=> {
          let info = {
            'nickName': _info.userInfo.nickName,
            'avatarUrl': "",
            'gender': _info.userInfo.gender
          };
          console.log("info:", info);
          this.loginbtn(info);
        },fail:(err)=>{
          console.log(err)
          wx.hideLoading({
            success: (res) => {},
          });
        }
      });
    }else{
      let _info = e.detail;
      let info = {
        'nickName': _info.userInfo.nickName,
        'avatarUrl': "",
        'gender': _info.userInfo.gender
      };
      console.log("info:兼容登录", info);
      this.loginbtn(info);
    }

  },
  loginbtn(_info) {
    console.log(this.data.logintap, "状态");
    var that = this;
    wx.login({
      success: async (_json) => {
        console.log(_info, _json.code, "login登录成功，获取用户info");
        if (_json.code) {
          let obj = {
            code: _json.code,
            info: _info,
            ver: "2",
            login_param: app.globalData.loginScene,
          };
          let res;
          try {
            res = await app.requestServerData(app.getNetAddresss("member.login.index"),'get',obj);
            console.log(res.data,'ddddddddddddddddddddd')
            setTimeout(() => {
              that.setData({
                logintap: false
              });
            }, 1000);
            let _data = res.data;
            if(res.data.result){
              try {
                // 存储key
                if (_data.data.user_info) {
                  wx.setStorageSync("nickname", _data.data.user_info.nickname);
                }
                if(_data.data.session){
                  wx.setStorageSync('session', _data.data.session);
                }
                if(_data.data.openid) {
                  wx.setStorageSync('openid', _data.data.openid);
                }
                if(_data.data.wx_token){
                  wx.setStorageSync('wx_token', _data.data.wx_token);
                }
                if(_info){
                  wx.setStorageSync('userInfo', _info);
                }
                if(_data.data.uid){
                  wx.setStorageSync('yz_uid', _data.data.uid);
                }

                wx.hideLoading();
                if(this.options.extra_data) {
                  that.skipLogin();
                }
                if( _data.data.is_first_time_bind){
                  // 首次授权登录自动绑定手机号
                  that.setData({
                    showAutoBindPhone: true
                  });
                }else{
                  that.getInviteData();
                }

                wx.removeStorageSync("new_decorate"); //登录之后清除首页缓存数据重新请求
              } catch (e) {
                wx.reLaunch({
                  url: "/packageG/index/index",
                });
              }
            }else{
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: _data.msg,
                success(res) {
                  console.log(res);
                }
              });
              console.log("第三方登录数据错误" + res.errMsg);
            }
          } catch (res) {
            console.log('errrrrrrrrr',res)
            wx.hideLoading();
              wx.showToast({
                title: "第三方登录失败session、wx_token获取失败" + res.errMsg,
                duration:3000,
                icon:'none'
              });
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              console.log("第三方登录失败session、wx_token获取失败" + res.errMsg);
          }
          
        } else {
          this.setData({
            logintap: false,
          });
          wx.showToast({
            title: "获取用户登录态失败！" + res.errMsg,
            duration: 3000,
            icon: "none",
          });
          console.log("获取用户登录态失败！" + res.errMsg);
        }
      },
      fail: (res) => {
        wx.hideLoading();
        this.setData({
          logintap: false,
        });
        console.log("登录失败，请求被拒绝！获取用户登录态失败！" + res);
      },
    });
  },
  getInviteData() {
    this.getInvites();
  },
  async getData(){
    let res;
    try {
      res = await app.requestServerData(app.getNetAddresss("privacy-policy.index"),'get',{});
      console.log(res.data.result)
      let data = res.data.data;
      if(res.data.result){
        this.setData({
          shop_name:data.shop_name,
          register_protocol:data.register_protocol,
          platform_protocol:data.platform_protocol,
          default_head_img:data.shop_logo,
          themeStyle: `--themeBaseColor: ${data.theme_color};`,
          theme_color:data.theme_color
        })
        if (data.register_protocol && data.register_protocol.id && data.register_protocol.default_tick) {
          this.setData({
            checkedSelect:data.register_protocol.default_tick
          })
        }
      }
    } catch (error) {
      console.log(error)
    }
    // let urlStr = app.getNetAddresss("privacy-policy.index");
    // app._getNetWork({
    //   url: urlStr,
    //   success: (resdata)=> {
    //     var res = resdata.data;
    //     if (res.result == 1) {
    //       this.setData({
    //         shop_name:res.data.shop_name,
    //         register_protocol:res.data.register_protocol,
    //         platform_protocol:res.data.platform_protocol,
    //         default_head_img:res.data.shop_logo,
    //         themeStyle: `--themeBaseColor: ${res.data.theme_color};`,
    //         theme_color:res.data.theme_color
    //       })
    //       if (res.data.register_protocol && res.data.register_protocol.id && res.data.register_protocol.default_tick) {
    //         this.setData({
    //           checkedSelect:res.data.register_protocol.default_tick
    //         })
    //       }
    //     }
    //     wx.hideLoading();
    //   },
    //   fail: (res)=> {
    //     console.log(res);
    //   },
    // });
  },
  //是否开启邀请页面
  getInvites() {
    let urlStr = app.getNetAddresss("member.member.isValidatePage");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data;
          try {
            this.checktoInvite(data);
          } catch (e) {
            wx.reLaunch({
              url: "/packageG/index/index",
            });
          }

        }
        wx.hideLoading();
      },
      fail: (res)=> {
        console.log(res);
      },
    });
  },
  skipLogin(_isToPage){
    let urlStr = app.getNetAddresss("member.member.skip-login-request");
    app._getNetWork({
      url: urlStr,
      data: {
        extra_data: this.options.extra_data
      },
      success: (resdata)=> {
        if(_isToPage) {
          wx.reLaunch({
            url: "/packageG/index/index",
          });
        }
      },
      fail: (res)=> {
        console.log(res);
      },
    });
  },
  checkLogin() {
    let url = app.getNetAddresss("member.login.check-login");
    app._getNetWork({
      url: url,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.skipLogin(true);
        } else {
          app.tips(res.msg)
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // //初始化语言设置
  // initLanguage() {
  //   let urlStr = app.getNetAddresss("setting.get-lang-setting");
  //   app._getNetWork({
  //     url: urlStr,
  //     data: {},
  //     success: function (resdata) {
  //       var res = resdata.data;
  //       if (res.result == 1) {
  //         let data = res.data;
  //         try {
  //           wx.setStorageSync("mailLanguage", JSON.stringify(data));
  //         } catch (e) {
  //           console.log(e);
  //         }
  //       }
  //     },
  //     fail: function (res) {
  //       console.log(res);
  //     },
  //   });
  // },

  // behaviors有相同处理函数
  // gotourl() {
  //   try {
  //     if (!this.data.yzredirect) {
  //       this.gomember();
  //     } else {
  //       if (this.data.yzredirect.indexOf("login/login") > 0) {
  //         this.gomember();
  //       } else {
  //         wx.reLaunch({
  //           url: "/" + this.data.yzredirect,
  //           fail:function(err){
  //             // 防止跳转不了 尝试直接指向会员中心
  //             wx.reLaunch({
  //               url: '/packageG/member_v2/member_v2',
  //             });
  //           }
  //         });
  //       }
  //     }
  //   } catch (e) {
  //     wx.reLaunch({
  //       url: "/packageG/index/index",
  //     });
  //   }
  // },

  gomember() {
    wx.reLaunch({
      url: "/packageG/member_v2/member_v2",
    });
    app.data.login_type = 1;
  },
  // 获取授权手机号
  async getPhoneNumber(e) {
    let info = e.detail;
    if(info.errMsg == 'getPhoneNumber:ok') {
      let mobile = await this.getPhone_index(info.code);
      this.data.AuthorizedPhone = mobile;
      await this.getPrepBind(mobile);
      await this.setBindPhone();
      this.getInviteData();
    }else{
      this.getInviteData();
    }
  },
  getPhoneM() {
    return new Promise((resolve,reject) => {
      wx.checkSession({
        success: (res) => {
          console.log(res, 'checkSession');
          resolve();
        },
        fail:err => {
          reject(err);
        }
      });
    });
  },
  getSessionKey() {
    let key = wx.getStorageSync('session');
    console.log(key, '缓存的session');
    let urlStr = app.getNetAddresss('member.mini-decrypt.getSessionKey');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          session_key_id: key,
          not_validate_page: '0'
        },
        showToastIn: false,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            console.log(res, '获取session_key');
            if (res.result == 1) {
              let keys = res.data.session_key_data.session_key;
              resolve(keys);
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  getPhone_index(info, keys) {
    wx.showLoading({
      title: '加载中',
    });
    // let arr = {
    //   info: info,
    //   session_key: keys
    // };
    let urlStr = app.getNetAddresss('member.member.miniMemberMobile');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          code: info,
          not_validate_page: '0'
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            resolve(res.data.phone_info.purePhoneNumber);
          } else {
            wx.hideLoading({
              success: (res) => { },
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  setBindPhone(mobile){
    wx.hideLoading({
      success: (res) => { },
    });
    let urlStr = app.getNetAddresss('member.member.bindMobile');
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          mobile: this.data.AuthorizedPhone,
          mini_first_time_bind: 1
        },
        success: (resdata)=> {
          var res = resdata.data;
          
          if(this.data.changidInfo && this.data.changidInfo.change_uid){
            // 更新uid为合并后的会员id
            wx.setStorage({
              key: "yz_uid",
              data: this.data.changidInfo.change_uid,
            });
          }
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          this.getInviteData();
          resolve();
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  closeChangeId() {
    this.setData({
      showChangeID: false
    });
  },
  //先验证是否导致会员id变更
  getPrepBind(mobile) {
    let urlStr = app.getNetAddresss("member.member.prepBind");
    return new Promise((resolve,reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          mobile: mobile
        },
        validateBol: 2,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.is_show) {
              // 显示 导致会员id变更 弹窗
              wx.hideLoading({
                success: (res) => {},
              });
              let basic_info = wx.getStorageSync('yz_basic_info');
              this.setData({
                balance:wx.getStorageSync('balance'),
                point:wx.getStorageSync('balance'),
                showChangeID: true,
                changidInfo: {
                  uid: res.data.uid,
                  change_uid: res.data.change_uid
                }
              });
            } else {
              resolve();
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject(res);
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
});
